package org.cary.lucene.search;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.cary.lucene.index.IndexReaderUtil;


public abstract class AbstractSearchEngine implements SearchEngine {
    
    private static String storePath = "D:/tmp/lucene/111";
    private Directory _storeDir;
	private static IndexSearcher _searcher = null;
	private static Analyzer _analyzer = null;

    /**
     * 进行高亮处理时,html片段的前缀
     */
    private String htmlPrefix = "<p>";
    /**
     * 进行高亮处理时,html片段的后缀
     */
    private String htmlSuffix = "</p>";

    public String getHtmlPrefix() {
        return htmlPrefix;
    }

    public void setHtmlPrefix(String htmlPrefix) {
        this.htmlPrefix = htmlPrefix;
    }

    public String getHtmlSuffix() {
        return htmlSuffix;
    }

    public void setHtmlSuffix(String htmlSuffix) {
        this.htmlSuffix = htmlSuffix;
    }
    
    protected IndexSearcher getSearcher() {
		if( _searcher != null ){
			return _searcher;		
		}
		IndexReader r = IndexReaderUtil.getIndexReader(storePath);
		_searcher = new IndexSearcher(r);
		return _searcher;
	}
    

    protected Directory getStoreDir() {
		if(_storeDir != null)
			return _storeDir;
		try {
			_storeDir = FSDirectory.open(Paths.get(storePath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return _storeDir;
	}
    
    //每次更新或者删除后，需要调用
    protected void reSetSearcher() {
    	try {
    		IndexSearcher searcher = getSearcher();
    		if(searcher == null)
    			return;
    		IndexWriterConfig iwConfig = new IndexWriterConfig(getAnalyzer());
    		IndexWriter indexWriter = new IndexWriter(getStoreDir(), iwConfig);
    		DirectoryReader dr = DirectoryReader.open(indexWriter);
    		IndexReader r = DirectoryReader.openIfChanged(dr);
			if(r == null){
				r = IndexReaderUtil.getIndexReader(storePath);
			}
			_searcher = new IndexSearcher(r);
					
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
    public static Analyzer getAnalyzer(){
		if(_analyzer != null){
			return _analyzer;
		}
		_analyzer = new StandardAnalyzer();
		return _analyzer;
	}
    
    public static void setAnalyzer(Analyzer analyzer){
    	_analyzer = analyzer;
    }
}
